package com.example.tv;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.media3.common.MediaItem;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.tv.adapter.TvAdapter;
import com.example.tv.entity.TvEntity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements TvAdapter.ItemOnClickListener, KeyEvent.Callback {
    LinearLayout menuBox;
    RecyclerView recyclerView;

    TvAdapter tvAdapter;

    ExoPlayer player;

    PlayerView playerView;

    long lastClickTime = 0L;

    List<TvEntity> cctvList;
    List<TvEntity> provinceList;

    List<TvEntity> playList;
    int playIndex = 0;

    private float mPosX;
    private float mPosY;
    private float mCurPosX;
    private float mCurPosY;

    Toast toast;

    LinearLayout use;

    @SuppressLint("ScheduleExactAlarm")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1、全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //操作说明
        use = findViewById(R.id.use);

        //存储配置，判断操作说明是否已读，如果已读，下次启动不再提示
        SharedPreferences config = getSharedPreferences("config", MODE_PRIVATE);
        if (!config.contains("use")) {
            use.setVisibility(View.VISIBLE);
            config.edit().putInt("use", 1).apply();
        }


        //菜单
        menuBox = findViewById(R.id.menu);
        player = new ExoPlayer.Builder(this).build();
        playerView = findViewById(R.id.play_view);
        playerView.setUseController(false);
        playerView.setPlayer(player);

        //2、初始化数据
        initBtnClicks();
        initTvData();
        recyclerView = findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        tvAdapter = new TvAdapter(this, cctvList, this);
        recyclerView.setAdapter(tvAdapter);

        //默认打开CCTV1
        itemClick(cctvList.get(0), 0);
    }

    private void initBtnClicks() {
        findViewById(R.id.cctv).setOnClickListener(v -> {
            tvAdapter.setLocalDataSet(cctvList);
            recyclerView.setAdapter(tvAdapter);
        });
        findViewById(R.id.province).setOnClickListener(v -> {
            tvAdapter.setLocalDataSet(provinceList);
            recyclerView.setAdapter(tvAdapter);
        });
    }

    void initTvData() {
        try {
            InputStream inputStream = getResources().openRawResource(R.raw.tv); // filename为要读取的txt文件名（不包含后缀）
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            playList = new ArrayList<>();
            cctvList = new ArrayList<>();
            provinceList = new ArrayList<>();
            String[] split = stringBuilder.toString().split("\n");
            for (String s : split) {
                String[] tv = s.split(",");
                TvEntity tvEntity = new TvEntity(tv[0], tv[1], tv.length > 2 ? tv[2] : null);
                if (tv[0].startsWith("CCTV")) {
                    cctvList.add(tvEntity);
                } else if (tv[0].endsWith("卫视")) {
                    provinceList.add(tvEntity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void itemClick(TvEntity tv, int position) {
        try {
            if (tv.getTitle().startsWith("CCTV")) {
                playList = cctvList;
            } else if (tv.getTitle().endsWith("卫视")) {
                playList = provinceList;
            }
            playIndex = position;
            showToast("正在播放：" + tv.getTitle());
            MediaItem mediaItem = MediaItem.fromUri(tv.getUrl());
            player.setMediaItem(mediaItem);
            player.prepare();
            player.play();
        } catch (Exception e) {
            showToast("播放失败：" + e.getMessage());
        }
    }

    /**
     * 触屏事件
     *
     * @param event The touch screen event.
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosX = event.getX();
                mPosY = event.getY();
                //点击右侧显示或隐藏菜单
                if (event.getX() > 700) {
                    toggleMenu();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                mCurPosX = event.getX();
                mCurPosY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                float Y = mCurPosY - mPosY;
                float X = mCurPosX - mPosX;
                //在左侧滑动，且左侧菜单未打开才执行切换频道
                if ((Math.abs(Y) > 70 || Math.abs(X) > 70) && event.getX() <= 700 && menuBox.getVisibility() == View.GONE) {
                    if (Math.abs(Y) > Math.abs(X)) {
                        if (Y > 0) {
                            downSlide();
                        } else {
                            upSlide();
                        }
                    } else {
                        if (X > 0) {
                            rightSlide();
                        } else {
                            leftSlide();
                        }
                    }
                }
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 显示菜单
     */
    private void showMenu() {
        menuBox.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(menuBox, "translationX", -menuBox.getWidth(), 0);
        animator.setDuration(300);
        animator.start();
    }

    /**
     * 隐藏菜单
     */
    private void hideMenu() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(menuBox, "translationX", 0, -menuBox.getWidth());
        animator.setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                menuBox.setVisibility(View.GONE);
            }
        });
        animator.start();
    }

    /**
     * 显示或隐藏菜单
     */
    private void toggleMenu() {
        int visibility = menuBox.getVisibility();
        if (visibility == View.VISIBLE) {
            hideMenu();
        } else {
            showMenu();
        }
    }


    /**
     * 按键事件
     *
     * @param event The key event.
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (event.getKeyCode()) {
                // 处理确认键的逻辑代码
                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    use.setVisibility(View.VISIBLE);
                    break;
                case KeyEvent.KEYCODE_DPAD_UP:
                    upSlide();
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    downSlide();
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    leftSlide();
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    rightSlide();
                    break;
                case KeyEvent.KEYCODE_BACK:
                    hideMenu();
                    break;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 上滑
     */
    private void upSlide() {
        // 处理向上方向键的逻辑代码
        if (playIndex < playList.size() - 1) {
            itemClick(playList.get(playIndex + 1), playIndex + 1);
        } else {
            showToast("最后一个频道");
        }
    }

    /**
     * 下滑
     */
    private void downSlide() {
        // 处理向下方向键的逻辑代码
        if (playIndex > 0) {
            itemClick(playList.get(playIndex - 1), playIndex - 1);
        } else {
            showToast("第一个频道");
        }
    }

    /**
     * 展示toast
     *
     * @param message
     */
    void showToast(String message) {
        if(toast != null){
            toast.cancel();
        }
        toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        toast.getView().setBackgroundResource(R.drawable.toast_bg);
        TextView text = toast.getView().findViewById(android.R.id.message);
        text.setTextColor(Color.WHITE);
        toast.show();
    }

    /**
     * 右滑
     */
    private void rightSlide() {
        // 处理向右方向键的逻辑代码
        itemClick(provinceList.get(0), 0);
    }

    /**
     * 左滑
     */
    private void leftSlide() {
        // 处理向左方向键的逻辑代码
        itemClick(cctvList.get(0), 0);
    }

    /**
     * 系统返回
     */
    @Override
    public void onBackPressed() {
        use.setVisibility(View.GONE);
        if (System.currentTimeMillis() - lastClickTime < 300) {
            super.onBackPressed();
            finish();
            System.exit(0);
            return;
        }
        lastClickTime = System.currentTimeMillis();
    }
}